package com.fengpanlong.web;


import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fengpanlong.dao.EmployeeDao;
import com.fengpanlong.dao.FileDao;
import com.fengpanlong.dao.FiletypeDao;
import com.fengpanlong.entity.Employee;
import com.fengpanlong.entity.EmployeeProject;
import com.fengpanlong.entity.Filetype;
import com.fengpanlong.util.StringUtil;

public class FileShareServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getMethod();
		String m = request.getParameter("_m");
		if("GET".equals(method)){
			if("".equals(m) || m == null) {
				sharefile(request,response);
				} else if("bulid".equals(m)) {
					newfile(request,response);
				}  
			} else {
				if("save".equals(m)) {
					savefile(request,response);
				} if("".equals(m) || m == null ) {
					sharefile(request,response);
				}
			}
		}
	
	
	

	private void savefile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		EmployeeProject ep = (EmployeeProject)request.getSession().getAttribute("ep");
		String projectid = ep.getProjectId();
		String employeeid = ep.getEmployeeId();
		Employee employee = new EmployeeDao().findById(employeeid);
		String name = request.getParameter("name");
		Filetype filetype = new Filetype();
		filetype.setName(name);
		String id = StringUtil.getId();
		String time = StringUtil.formateTime();
		filetype.setCreatetime(time);
		filetype.setEmployee(employee);
		filetype.setProjectId(projectid);
		filetype.setId(id);
		FiletypeDao filetypedao = new FiletypeDao();
		filetypedao.save(filetype);
		response.sendRedirect("fileshare.jspx");
	}




	private void newfile(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
	
		request.getRequestDispatcher("/WEB-INF/views/newfile.jsp").forward(request, response);
	}

	private void sharefile(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException{
		EmployeeProject ep = (EmployeeProject)request.getSession().getAttribute("ep");
		String projectid = ep.getProjectId();
		EmployeeDao edao = new EmployeeDao();
		FiletypeDao typedao = new FiletypeDao();
		List<Filetype> list =  typedao.findAll(projectid);
		for(Filetype filetype : list) {
			String employeeid = filetype.getEmployeeId();
			Employee e = edao.findById(employeeid);
			filetype.setEmployee(e);
			
		}
		request.setAttribute("filetype",list);
		request.getRequestDispatcher("WEB-INF/views/file.jsp").forward(request, response);
		
	}
	
	

}
